/**
 *mail service
 * */

var nodemailer = require('nodemailer'),
  encryptor = require('../util').encryptor,
  weixinuserDao = require('../db/daos/weixinuser'),
  config = require('../util').config,
  sandbox = require('../util').sandbox,
  https = require('https'),
  util = require('../util'),
  log = require('../util').log;
Promise = require('bluebird');

var sendMail = function (msg) {
  var to = msg.to,
      openid = msg.openid;
  return new Promise(function (resolve, reject) {
    try {
      var transporter = nodemailer.createTransport(config.mailServer, config.mailSender);
      var info = {
        time: (new Date()).getTime(),
        openid: openid
      };

      log.consoleLogger.info("****mail will be sended to " + to + "****");

      transporter.sendMail({
        to: to,
        subject: '验证信息',
        text: '请点击下面链接，激活您的邮箱：' + config.appHost + '/mail/callback?mailToken=' + encryptor.encode(info)
      }, function (error, info) {
        if (error) {
          log.consoleLogger.error("****mail send to " + to + " failed ****");
          log.errLogger.error(error);
          return reject(error);
        }
        log.consoleLogger.info('Mail sent: ' + info.response);
        return resolve(info.response);
      });
    } catch (e) {
      log.log2Error(e);
      return reject(e);
    }
  });

};

var sendWeixin = function (options) {

  //make post http request
  var post = function (options, accessToken,callback) {
    try {
      var postData = JSON.stringify({
        "touser": options.openid,
        "msgtype": "text",
        "text": {
          "content": "您已成功激活邮箱"
        }
      });

      var options = {
        hostname: 'api.weixin.qq.com',
        port: 443,
        path: '/cgi-bin/message/custom/send?access_token=' + accessToken.access_token,
        method: 'POST',
        headers: {
          'Content-Type': 'application/json; charset=UTF-8'
        }
      };

      var req = https.request(options, function (res) {
        res.setEncoding('utf8');
        var chunkData;
        res.on('data', function (chunk) {
          chunkData = chunk;
        });
        res.on('end', function () {
          console.log('客服接口调用完毕,返回值如下:');
          console.log(chunkData);
          if(callback){
            callback(res.statusCode,chunkData);
          }
        })
      });

      req.on('error', function (e) {
        log.errLogger.error('problem with request: ' + e.message);
      });

      // write data to request body
      req.write(postData);
      req.end();
    } catch (e) {
      log.log2Error(e);
    }

  };

  return util.weixin.getAccessToken(options.openid).then(post.bind(undefined, options), function (err) {
    log.errLogger.error(err);
  });

};

var handleCallback = function (mailToken) {
  try {
    var info = encryptor.decode(mailToken);
  } catch (e) {
    log.log2Error(e);
    return Promise.resolve('请关注微信后，回复邮箱获取验证链接！');
  }
  if (((new Date()).getTime() - info.time) < config.mailTokenStayTime) {
    register_date = Date.now();

    // 根据注册时间从新计算过期时间
    due_date = register_date + util.config.free_duration;

    return weixinuserDao.findOneAndUpdate({'openid': info.openid}, {'certificated': true,'register_date':register_date,'due_date':due_date});
  } else {
    return Promise.resolve('验证信息已过期，请重新获取验证信息！');
  }
};

sandbox.on(sandbox.MSG.MAIL_VERIFICATION, sendMail);
sandbox.on(sandbox.MSG.MAIL_SUCCESS, sendWeixin);

module.exports = {
  sendMail: sendMail,
  sendWeixin: sendWeixin,
  handleCallback: handleCallback
};